package com.david.andserver.util;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import com.david.andserver.NetInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

/**
 * 用于获取磁盘中文件列表，如音乐，图片，视频等
 *
 * TODO 手机music及图片从contentProvider中获取
 * */
public class FileUtils {
    public static String musicString = "";
    public static String videoString = "";
    public static void getMusic(Context context) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                ArrayList<Song> list = new ArrayList<>();

                Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                        , null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

                if (cursor != null) {
                    Song song;
                    while (cursor.moveToNext()) {

                        song = new Song();
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));

                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                        String singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                        if (new File(path).exists()) {//歌曲可能不存在，
                            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                            long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                            long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
                            //list.add(song);
                            //把歌曲名字和歌手切割开
                            //song.setName(name);
                            song.setSinger(singer);
                            song.setPath(path);
                            song.setDuration(duration);
                            song.setSize(size);
                            song.setId(id);
                            song.setAlbumId(albumId);
//                            song.setAlbumImgPath(getAlbumArt(MusicApplication.Companion.instance(), albumId));


                            if (singer == null || "<unknown>".equals(singer) || name.contains("-")) {
                                if (name.contains("-")) {
                                    String[] str = name.split("-");
                                    singer = str[0].trim();
                                    song.setSinger(singer);
                                    name = str[1].trim();
                                    song.setName(name.trim());
                                } else {
                                    song.setName(name.trim());
                                    song.setSinger(name.trim().substring(0,name.lastIndexOf(".")));
                                }
                            } else {
                                song.setName(name.trim());
                                song.setSinger(name.trim().substring(0,name.lastIndexOf(".")));
                            }

                            list.add(song);
                        }
                    }

                    if (list.size() == 0) {
                        return;
                    }
                    Collections.sort(list);
                    while ('#'==(list.get(0).sortChar)) {
                        Song tempSong = list.remove(0);
                        list.add(tempSong);

                    }
                    //{"size":30, "data":[]}
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("{\"size\":").append(list.size()).append(",\"data\":[");
                    for (int i = 0;i<list.size();++i){
                        list.get(i).path = "http://" + NetInfo.getIpAddress(context) + ":8080" + list.get(i).path.substring(list.get(i).path.indexOf("0")+1);
                        stringBuilder.append(list.get(i).toJsonString());
                        if (i < (list.size() - 1))
                            stringBuilder.append(",");
                    }
                    stringBuilder.append("]}");
                    musicString = stringBuilder.toString();
                }
                if (cursor != null) {
                    cursor.close();
                }
            }
        }.start();
    }

    public static void getVideo(Context context) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                ArrayList<VideoBean> list = new ArrayList<>();

                Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                        , null, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);

                if (cursor != null) {
                    VideoBean videoBean;
                    while (cursor.moveToNext()) {

                        videoBean = new VideoBean();
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));

                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
                        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                        if (new File(path).exists()) {
                            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                            long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
                            videoBean.duration = duration;
                            videoBean.name = name;
                            videoBean.id = id;
                            videoBean.size = size;
                            videoBean.path = path;

                            list.add(videoBean);


                        }
                    }

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("{\"size\":").append(list.size()).append(",\"data\":[");
                    for (int i = 0;i<list.size();++i){
                        list.get(i).path = "http://" + NetInfo.getIpAddress(context) + ":8080" + list.get(i).path.substring(list.get(i).path.indexOf("0")+1);
                        stringBuilder.append(list.get(i).toJsonString());
                        if (i < (list.size() - 1))
                            stringBuilder.append(",");
                    }
                    stringBuilder.append("]}");
                    videoString = stringBuilder.toString();
                }
                if (cursor != null) {
                    cursor.close();
                }
            }
        }.start();
    }

    /**
     * File的比较方法会区分大小写，此处都转为小写进行比较
     * */
    public static void sortFile(File[] files){
        for (int i = 0;i<files.length;++i) {
            for (int j = 0;j<files.length-1-i;++j) {
                if (files[j].getPath().toLowerCase().compareTo(files[j + 1].getPath().toLowerCase()) > 0) {
                    File temp = files[j];
                    files[j] = files[j+1];
                    files[j+1]= temp;
                }
            }
        }
    }
}
